<?php

namespace app\index\controller\v1\douyin;

use app\common\controller\DouyinController;
use app\common\model\platform\PlatformAppOpen;
use hiduoke\services\douyinMinApp\API\DouyinOpenApi;
use hiduoke\services\douyinMinApp\DouyinMinAppServer;
use think\App;

class Open extends DouyinController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index()
    {
        return $this->success('ok');
    }

    /**
     * 授权事件接收 URL
     * Create by :  刘泓宾<514660094@qq.com>
     * @return string|\think\response\Json
     */
    public function event()
    {
        $Encrypt = input('Encrypt', '');
        if (!$Encrypt) {
            return $this->error('无Encrypt');
        }
        $id = input('id', 0);
        $open = (new PlatformAppOpen())->where(['id' => $id])->find();
        if (!$open) {
            return $this->error('未找到平台小程序');
        }
        $this->DY = new DouyinOpenApi($open['config']);
        $decrypt = $this->DY->getEventDecrypt($Encrypt);
        switch ($decrypt['Event']) {
            case "PUSH":
                $other_data = $open->other_data ?? [];
                $other_data['component_access_token'] = $this->DY->getComponentAccessToken($decrypt['Ticket'])['component_access_token'];
                $other_data['component_access_token_v2'] = $this->DY->getComponentAccessTokenV2($decrypt['Ticket'])['component_access_token'];
                $open->other_data = $other_data;
                $open->save();
                break;
            case "UPDATE_AUTHORIZED":
                break;
        }
        return 'success';
    }

    /**
     * Create by :  刘泓宾<514660094@qq.com>
     * @return string
     */
    public function call_back()
    {
        $authorization_code = input('authorization_code', '');
        $platform_app_id = input('appid', 0);
        $DYServer = new DouyinMinAppServer($platform_app_id);
        $res = $DYServer->getOpenApi()->getAuthorizerAccessToken($DYServer->component_access_token, $authorization_code);
        if (isset($res['errno'])) {
            return showMessage($res['message'], 'error', ['show_btn' => false, 'second' => -1]);
        }
        $platform_app = $DYServer->getPlatformApp();
        $platform_app->other_data = $res;
        $platform_app->server_config = [
            'auth_type'        => 1,
            'authorizer_appid' => $res['authorizer_appid'],
        ];
        $platform_app['appid'] = $res['authorizer_appid'];
        $platform_app->save();
        return showMessage('授权成功,请关闭当前页面', 'success', '', 0,
            ['show_btn' => false, 'second' => -1, 'title' => '授权成功,请关闭当前页面']);
    }


    /**
     * 消息与事件接收 URL
     */
    public function message_event()
    {
        return $this->success('', input());
    }
}
